﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Controls;

/// <summary>
/// ItemsControl类的扩展方法类
/// </summary>
public static class ItemsControlExtensions
{
    /// <summary>
    /// 通过数据模板的可视元素查找承载数据模板的子项容器对象
    /// </summary>
    /// <param name="itemsControl">ItemsControl以及从ItemsControl派生的对象</param>
    /// <param name="child">子元素(数据模板中的子元素)</param>
    /// <returns>承载数据模板的子元素容器，诸如ListBoxItem、ComboBoxItem 等等</returns>
    public static UIElement GetItemContainerFromChildElement(this ItemsControl itemsControl, UIElement child)
    {
        if (itemsControl.Items.Count > 0)
        {
            //查找ItemsPanel
            Panel panel = VisualTreeHelper.GetParent(itemsControl.ItemContainerGenerator.ContainerFromIndex(0)) as Panel;

            if (panel != null)
            {
                UIElement parent;
                do
                {
                    parent = VisualTreeHelper.GetParent(child) as UIElement;
                    if (parent == panel)
                    {
                        return child;
                    }
                    child = parent;
                }
                while (parent != null);
            }
        }
        return null;
    }
}
